<template>
  <div
    :style="{ overflow: tipVisible && isMobile() ? 'hidden' : '' }"
    v-if="courseSubmitTabList"
  >
    <div class="header">
      <!-- <div class="title">课程大类A</div> -->
      <template v-if="courseSubmitTabList">
        <div class="pc-nav no-scrollbar">
          <div class="nav" ref="pcNavRef">
            <div
              class="nav-item"
              :class="navActiveIndex == index ? 'active' : ''"
              v-for="(item, index) in courseSubmitTabList"
              :key="item?.course_ku_id"
              @click="onClickNavItem(index)"
            >
              {{ item?.course_ku_title }}
            </div>
          </div>
        </div>
        <div class="mobile-nav" ref="childMobileNavRef">
          <template v-if="courseSubmitTabList">
            <div
              class="active-nav"
              @click.stop="mobileNavVisible = !mobileNavVisible"
            >
              <span>{{
                courseSubmitTabList[navActiveIndex]?.course_ku_title
              }}</span>
              <IconArrowRight2 class="arrow-right"></IconArrowRight2>
            </div>
            <div class="select-nav" :class="mobileNavVisible ? 'show' : ''">
              <div
                class="select-item"
                v-for="(item, index) in courseSubmitTabList"
                @click.stop="onClickNavItem(index)"
                :key="item?.course_ku_id"
                :class="navActiveIndex == index ? 'active' : ''"
              >
                {{ item?.course_ku_title }}
              </div>
            </div>
          </template>
          <template v-else>
            <div class="mobile-skeleton">
              <div class="mobile-skeleton-inner">
                <Skeleton width="500px"></Skeleton>
              </div>
            </div>
          </template>
        </div>
      </template>
      <template v-else>
        <div class="pc-skeleton">
          <div class="pc-skeleton-inner">
            <Skeleton height="30px" width="100px"></Skeleton>
            <Skeleton height="30px" width="100px"></Skeleton>
            <Skeleton height="30px" width="100px"></Skeleton>
          </div>
        </div>
      </template>
    </div>
    <template
      v-if="
        trainingList &&
        trainingList.length > 0 &&
        courseSubmitTabList?.length > 0
      "
    >
      <div
        class="progress-status no-scrollbar"
        :style="{
          'overflow-x': tipVisible ? 'visible' : 'auto',
          '--line-width': progressLineWidth,
          '--line-offset-left': progressLineOffsetLeft,
        }"
        ref="progressBarRef"
      >
        <div class="point-tip-mask" v-if="tipVisible"></div>
        <template v-if="trainingList">
          <div
            class="progress-item"
            :class="index == activeNum ? 'show-logo active-dot' : ''"
            v-for="(item, index) in trainingList"
            :key="item.id"
          >
            <div
              class="progress-item-inner"
              @click="changeProgressBar(item.id, index)"
            >
              <div class="user-logo">
                <div class="nickname">
                  {{ memberStore.profile?.last_name +' '+ memberStore.profile?.first_name }}
                </div>
                <img
                  class="logo"
                  v-logo-error
                  :src="memberStore.profile?.headimgurl"
                  alt=""
                  v-if="memberStore.profile?.headimgurl"
                />
                <img
                  class="logo"
                  src="~/assets/images/user-logo/default_logo.jpg"
                  alt=""
                  v-else
                />
              </div>
              <div class="relative" style="width: 100%">
                <div class="dot"></div>
                <template
                  v-if="
                    trainingList.length > 1 &&
                    ((index == 1 && tipVisible) ||
                      (trainingList.length - 1 == index && tipVisible))
                  "
                >
                  <IconPointTip class="svg cursor-svg" />
                  <div
                    class="point-tip-dialog"
                    :class="index == 1 ? 'point-start-tip' : ''"
                    :id="
                      trainingList.length - 1 == index ? 'point-tip-end' : ''
                    "
                    @click.stop=""
                  >
                    <span
                      class="wave"
                      v-for="i in 4"
                      :key="i"
                      :style="`--i: ${i}`"
                    ></span>
                    <a-button
                      class="click"
                      type="primary"
                      @click="onClickContinue"
                      >{{
                        isContinued
                          ? $t("btnText.complete")
                          : $t("btnText.click_continue")
                      }}</a-button
                    >
                  </div>
                </template>
              </div>
              <div class="progress-title" :title="item.title">
                {{ item.title }}
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="pc-skeleton flex-1">
            <Skeleton height="100px" block></Skeleton>
          </div>
          <div class="mobile-skeleton flex-1">
            <Skeleton height="300px" block></Skeleton>
          </div>
        </template>
      </div>
      <ExamBasicExam></ExamBasicExam>
    </template>
    <!-- <ExamLicenseApply v-if="activeNum === 1"></ExamLicenseApply> -->
  </div>
  <NoData v-if="courseSubmitTabList && courseSubmitTabList.length == 0" />
</template>

<script setup lang="ts">
import {
  inject,
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  provide,
  ref,
} from "vue";
import { postCourseSubmitTab, postTraining } from "../../../api/aviation";
import type {
  CourseSubmitTabItem,
  CourseTrainingItem,
} from "../../../types/aviation";
import { useCacheStore, useMemberStore } from "../../../store";
import { watch } from "vue";
const memberStore = useMemberStore();
const cacheStore = useCacheStore();
const progressBarRef = ref<HTMLElement | undefined>();
const activeNum = ref(0);
const trainingId = ref(-1);
provide("trainingId", trainingId);
const changeProgressBar = (traing_id: number, index: number) => {
  if (activeNum.value == index) return;
  activeNum.value = index;
  trainingId.value = traing_id;
  let progressItems = (progressBarRef.value as HTMLElement).querySelectorAll(
    ".progress-item"
  );
  progressItems.forEach((item) => {
    item.classList.remove("active");
  });
  progressItems.forEach((item, i) => {
    if (i < index) {
      nextTick(() => {
        item.classList.add("active");
      });
    }
  });
};

const progressLineWidth = ref("");
const progressLineOffsetLeft = ref("");
const initProgressLineWidth = () => {
  let progressBar = progressBarRef.value as HTMLElement;
  let progressItems = progressBar.querySelectorAll(".progress-item");
  if (progressItems.length <= 1) return;
  let lineWidth: number = 0;
  progressItems.forEach((item: HTMLElement, index, rawArr) => {
    if (index == 1) {
      let prevItemOffsetLeft = (rawArr[index - 1] as HTMLElement).offsetLeft;
      let currentOffsetLeft = item.offsetLeft;
      let { offsetLeft: dotOffsetLeft, offsetWidth: dotOffsetWidth } =
        item.querySelector(".dot");
      lineWidth =
        currentOffsetLeft -
        prevItemOffsetLeft +
        dotOffsetLeft +
        dotOffsetWidth / 2;
      progressLineOffsetLeft.value = item.offsetWidth / 2 + "px";
    }
  });
  progressLineWidth.value = lineWidth + "px";
};

const tipVisible = ref();
const isContinued = ref(false);
tipVisible.value = memberStore.getTipVisible();
let needResizePosition = tipVisible.value;
const onClickContinue = () => {
  if (isMobile()) {
    tipVisible.value = false;
    return;
  }
  if (!isContinued.value) {
    isContinued.value = true;
    setTipDialogPosition();
  } else {
    // end
    document.body.style.overflow = "";
    tipVisible.value = false;
  }
};

const transition_time = 1;
// flag 判断是否是 windows resize 事件
const setTipDialogPosition = (flag = false) => {
  if (!isContinued.value) return;
  let startTipDom = document.querySelector(".point-start-tip") as HTMLElement;
  if (startTipDom.style.transform.includes("vw")) return;
  let startCursorSvg = startTipDom.parentNode?.querySelector(
    ".cursor-svg"
  ) as HTMLElement;

  if (flag) {
    startTipDom.style.transition = `none`;
    startCursorSvg.style.transition = `none`;
    return;
  }
  let endTipDom = document.querySelector("#point-tip-end") as HTMLElement;
  let endCursorSvg = endTipDom.parentNode?.querySelector(
    ".cursor-svg"
  ) as HTMLElement;
  const { left } = endTipDom?.getBoundingClientRect();
  let offsetLeft = left - startTipDom.getBoundingClientRect().left;
  let cursorOffsetLeft =
    endCursorSvg.getBoundingClientRect().left! -
    startCursorSvg?.getBoundingClientRect()?.left!;
  startTipDom.style.transition = `transform ${transition_time}s ease-in-out`;
  startCursorSvg.style.transition = `left ${transition_time}s ease-in-out`;
  startTipDom.style.transform = `translate(calc(-50% + ${offsetLeft}px), -50%)`;
  startCursorSvg.style.left = `calc(50% + 0.7813vw + ${cursorOffsetLeft}px)`;
};
const resetTipDialogPosition = () => {
  setTipDialogPosition(true);
};

onBeforeMount(() => {
  getCourseSubmitTabData();
});
onMounted(() => {
  if (tipVisible.value && !isMobile()) {
    document.body.style.overflow = "hidden";
  }
  if (needResizePosition) {
    window.addEventListener("resize", resetTipDialogPosition);
  }
  window.addEventListener("resize", initProgressLineWidth);
  window.addEventListener("resize", initParentMobileNavWidth);
});

onBeforeUnmount(() => {
  if (needResizePosition) {
    window.removeEventListener("resize", resetTipDialogPosition);
  }
  if (!tipVisible.value) {
    memberStore.setTipVisibleEndTime();
  }
  window.removeEventListener("resize", initProgressLineWidth);
  window.removeEventListener("resize", initParentMobileNavWidth);
});

const pcNavRef = ref();
const navActiveIndex = ref(0);
const courseSubmitTabList = ref<CourseSubmitTabItem[]>();
provide("navActiveIndex", navActiveIndex);
provide("courseSubmitTabList", courseSubmitTabList);
const getCourseSubmitTabData = async () => {
  let res = await postCourseSubmitTab();
  if (res.code === 200) {
    courseSubmitTabList.value = res.data || [];
    cacheStore.profileData.exam.courseList = res.data;
    if (courseSubmitTabList.value.length > 0) {
      getTrainingData();
      nextTick(() => {
        useTouchXScroll(pcNavRef.value);
        initParentMobileNavWidth();
      });
    }
  }
};

const childMobileNavRef = ref();
const childMobileNavWidth = inject("childMobileNavWidth");
const initParentMobileNavWidth = () => {
  if (!childMobileNavRef.value) return;
  childMobileNavWidth.value =
    childMobileNavRef.value.offsetWidth.toFixed(2) * 1;
};

watch(navActiveIndex, () => {
  getTrainingData();
});

const trainingList = ref<CourseTrainingItem[]>();
const getTrainingData = async () => {
  let course_id = courseSubmitTabList.value![navActiveIndex.value].course_id;
  let res = await postTraining(course_id);
  if (res.code === 200) {
    trainingList.value = res.data || [];
    if (res.data.length == 0) return;
    trainingId.value =
      activeNum.value == -1
        ? res.data[0].id
        : res.data[activeNum.value]?.id || "";

    nextTick(() => {
      initProgressLineWidth();
    });
  }
};

const mobileNavVisible = ref(false);
const onClickNavItem = (index: number) => {
  navActiveIndex.value = index;
  activeNum.value = 0;
  trainingId.value = -1;
  if (isMobile()) {
    mobileNavVisible.value = true;
  }
};
</script>
<style scoped lang="less">
@import url("./common.less");

.header {
  .pc-nav {
    overflow-x: scroll;
    touch-action: pan-x;
    .nav {
      .nav-item {
        white-space: nowrap;
      }
    }
  }
  .pc-skeleton-inner {
    display: flex;
    gap: 24px;
  }
}

.point-tip-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.05);
}
.progress-item {
  &.active-dot + div {
    .dot + .svg,
    .point-tip-dialog {
      visibility: visible;
    }
  }
  .dot + .svg {
    position: absolute;
    top: 50%;
    visibility: hidden;
    left: calc(50% + 15px);
    transform: rotate(-25deg) translate(-50%, -50%);
    width: 40px;
    height: 40px;
    z-index: 1;
    transition: left 0.5s ease-in-out;
    :deep(&) path {
      fill: #4c5a64;
    }
  }
}

.point-tip-dialog {
  // display: none;
  position: absolute;
  transition: transform 0.5s ease-in-out;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  width: 220px;
  background-color: rgba(0, 0, 0, 0.1);
  height: 170px;
  border-radius: 20px;
  .click {
    position: absolute;
    right: 0;
    bottom: 0;
    font-size: 11px !important;
    margin-bottom: 8px;
    margin-right: 8px;
    padding: 0 10px !important;
    height: 32px !important;
  }
  span.wave {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 10px;
    height: 10px;
    border-radius: 50%;
    // border: 1px solid #70818c;
    background-color: var(--yd-primary-color);
    opacity: 0;
    animation-name: wave_animate;
    animation: animate 2s linear infinite;
    animation-delay: calc(0.5s * var(--i));
  }
  @keyframes animate {
    0% {
      opacity: 0.5;
      height: 0;
      width: 0;
    }
    50% {
      opacity: 0.5;
    }
    100% {
      height: 70px;
      width: 70px;
      opacity: 0;
    }
  }
}

#point-tip-end {
  visibility: hidden;
}

@media screen and (max-width: 768px) {
  .progress-item {
    .dot + .svg {
      width: 200px;
      height: 200px;
      left: calc(50% + 70px);
    }
    .point-tip-dialog {
      width: 1400px;
      height: 900px;
      border-radius: 80px;
      .click {
        height: 180px !important;
        font-size: 64px !important;
        padding: 0 60px !important;
        margin-right: 30px;
        margin-bottom: 30px;
      }
      span.wave {
        width: 100px;
        height: 100px;
      }
      @keyframes animate {
        0% {
          opacity: 0.5;
          height: 0;
          width: 0;
        }
        50% {
          opacity: 0.5;
        }
        100% {
          height: 400px;
          width: 400px;
          opacity: 0;
        }
      }
    }
  }
}
</style>
